﻿namespace Away.Common.Utils;

/// <summary>
/// 树形对象
/// </summary>
public abstract class TreeBase<T>
{
    /// <summary>
    /// ID
    /// </summary>
    public virtual int Id { set; get; }
    /// <summary>
    /// 父ID
    /// </summary>
    public virtual int ParentId { set; get; }
    /// <summary>
    /// 子集
    /// </summary>
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public List<T>? Children { get; set; }
}

/// <summary>
/// 树形结构类
/// </summary>
public static class TreeBuilder
{
    /// <summary>
    /// 递归方式转树形
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    /// <param name="list">集合</param>
    /// <returns></returns>
    public static List<T> Build<T>(this List<T> list) where T : TreeBase<T>
    {
        var newList = list.Where(p => p.ParentId == 0).ToList();
        foreach (var item in newList)
        {
            item.Children = GetChildrens(list, item);
        }
        return newList;
    }
    /// <summary>
    /// 递归子集
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    /// <param name="list">集合</param>
    /// <param name="node">节点</param>
    /// <returns></returns>
    private static List<T>? GetChildrens<T>(List<T> list, T node) where T : TreeBase<T>
    {
        List<T> childrens = list.Where(p => p.ParentId == node.Id).ToList();
        foreach (var item in childrens)
        {
            item.Children = GetChildrens(list, item);
        }
        return childrens.Any() ? childrens : null;
    }
}